﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace SimpleMultipleFileUploader.Web
{
    /// <summary>
    /// Summary description for ImportDataReceiver
    /// </summary>
    public class ImportDataReceiver : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            
            //Check to see if filename query parameter exists.
            //ToDo: Throw a meaningful error.
            if (context.Request.QueryString["filename"] == null)
                return;

            //Check to see if the foldername query parameter exists.
            //ToDo: Throw a meaningful error.
            if (context.Request.QueryString["foldername"] == null)
                return;

            string fileName = context.Request.QueryString["filename"].ToString();
            string folderName = context.Request.QueryString["foldername"].ToString();
            string fileFolderPath = context.Server.MapPath(string.Format("~/App_Data/{0}", folderName));
            
            //Check to see if the specified directory exists.
            //And if it doesn't, create a new one.
            if (!Directory.Exists(fileFolderPath))
            {
                Directory.CreateDirectory(fileFolderPath);
            }

            //Create the file under the specified folder.
            using (FileStream fs = File.Create(context.Server.MapPath(string.Format("~/App_Data/{0}/{1}", folderName, fileName))))
            {
                
                //Save the file from the input stream.
                using (Stream stream = context.Request.InputStream)
                {

                    byte[] buffer = new byte[4096];
                    
                    int bytesRead;

                    while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        fs.Write(buffer, 0, bytesRead);
                    }

                    stream.Flush();
                    stream.Close();
                }

                fs.Close();
            }

            
             
        }

        private void SaveFile(Stream stream, FileStream fs)
        {
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
            {
                fs.Write(buffer, 0, bytesRead);

            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}